package com.itboye.mengwu.app.ui.main;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.ImageCompressAndUpload;
import com.itboye.core.utils.ImageCompressAndUpload.OnUploadlistener;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.SoftwareUtil;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.MainApplication;
import com.itboye.mengwu.app.adapter.OrderGoodsCommentAdapter;
import com.itboye.mengwu.buy.ui.OrderFragment;
import com.itboye.mengwu.data.model.OrderQueryModel.OrderList;
import com.itboye.mengwu.data.presenter.OrderPresenter;
import com.itboye.mengwu.luntan.comment.adapter.GridViewAdapter;
import com.itboye.mengwu.luntan.comment.view.MyListView;
import com.itboye.mengwu.testpic.ui.PhotoActivity;
import com.itboye.mengwu.widget.MyGridView;
import com.itboye.mengwu.widget.PhotoSelectFragment;
import com.itboye.mengwu.widget.PhotoSelectFragment.PhotoSelectListener;
import com.umeng.common.message.Log;

public class PingLunBaoBeiActivity extends BaseActivity implements Observer {
	public final int EXTERNAL_CAMERA_REQ_CODE = 11;
	public final int EXTERNAL_STORE_REQ_CODE = 12;
	PopupWindows popupWindows;
	private MyGridView aiWuJiaGridView;
	private GridViewAdapter adapter;
	// private TextView activity_selectimg_send;
	// private ImageView imgPublishBack;
	// 标题
	private EditText edttitle;
	// 内容
	private EditText edtcontext;
	// private String title;
	private String contextEd;
	TextView txt_save;

	public final static int HU = 1;
	TextView ask, share;

	ImageView back;
	TextView txt_title, txt_cancel;
	Button btn_ok;
	ArrayList<String> imgUrls = new ArrayList<>();
	OrderList orderList = new OrderList();
	String type;
	LinearLayout goodsgroup;
	MyListView goodsCommentList;
	OrderGoodsCommentAdapter adapter2;
	private View parentView;
	int index;
	HashMap<String, String> hashMap = new HashMap<>();
	int position1, position2;
	int zz = 0;
	String[] comment = new String[] {};// 多商品的评价内容
	ArrayList<String> ids1 = new ArrayList<String>();// 多商品的id
	StringBuffer pskuId = new StringBuffer();// 多商品的规格
	StringBuffer pid = new StringBuffer();// 多商品的id
	StringBuffer groupId = new StringBuffer();// 多商品的分组ID
	StringBuffer packageId = new StringBuffer();// 多商品的分组ID
	String orderCode = "";// 订单编号
	StringBuffer scores = new StringBuffer();// 多个商品的评分
	String expressScore;
	String deliveryScore;
	String serviceScore;
	private StringBuffer buffer = new StringBuffer();// 多商品评论的图片
	ArrayList<String> ids2 = new ArrayList<String>();
	private int childPosition;
	private int parentPosition;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		parentView = LayoutInflater.from(this).inflate(
				R.layout.activity_pinglunbaobei, null);
		return R.layout.activity_pinglunbaobei;
	}

	@Override
	public void onMyCreate() {
		// tanPresenter = new TieZiPresenter(this);
		txt_title.setText("评论宝贝");
		txt_cancel.setText("发布");
		orderList = (OrderList) getIntent().getSerializableExtra("model");
		adapter2 = new OrderGoodsCommentAdapter(this, orderList, imgUrls,
				clickListener);
		goodsCommentList.setAdapter(adapter2);
		orderPresenter = new OrderPresenter(this);
		Init();

	}

	protected ArrayList<String> uploadedUrl = new ArrayList<String>();
	protected OrderPresenter orderPresenter;
	protected String uid;
	int position = 0;

	public void Init() {
		uid = SPUtils.get(this, null, SpPublicParams.UID, "") + "";
		type = getIntent().getStringExtra("type");
		txt_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				getEditTextValue();
				onBitMap();
			}
		});
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}

	protected void getEditTextValue() {
		// TODO Auto-generated method stub
		orderCode = orderList.getOrderCode();
		comment = new String[orderList.getItems().size()];
		for (int i = 0; i < orderList.getItems().size(); i++) {
			ViewGroup group = (ViewGroup) goodsCommentList.getChildAt(i);
			EditText editText = (EditText) group.findViewById(R.id.edtcontext);
			RatingBar ratingBar = (RatingBar) group
					.findViewById(R.id.miaoshuRb);
			scores.append(ratingBar.getNumStars() + ",");
			pid.append(orderList.getItems().get(i).getPId() + ",");
			comment[i] = editText.getText().toString() == null ? "" : editText
					.getText().toString();
			System.out.println("我是评论内容" + comment[i]);
			pskuId.append(orderList.getItems().get(i).getPskuId() + ",");
			groupId.append(orderList.getItems().get(i).getGroupId() + ",");
			packageId.append(orderList.getItems().get(i).getPackageId() + ",");

		}
	}

	OnItemClickListener clickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			ByAlert.alert("" + view.getTag());
			index = position;
			if (position == imgUrls.size()) {
				SoftwareUtil.showOrHideSoftware(view, MainApplication.context,
						false);
				popupWindows = new PopupWindows(PingLunBaoBeiActivity.this,
						parentView);
			} else {
				Intent intent = new Intent(PingLunBaoBeiActivity.this,
						PhotoActivity.class);
				intent.putExtra("imgUrls", imgUrls);
				intent.putExtra("ID", position);
				startActivity(intent);
			}
		}
	};

	public void choosePhoto(int parentPostion, int childPosition) {
		this.childPosition = childPosition;
		this.parentPosition = parentPostion;
		if (orderList.getItems().get(parentPostion).getImgUrls().size() == childPosition) {
			
			new PopupWindows(PingLunBaoBeiActivity.this, parentView);
		} else {
			// Intent intent = new Intent(PingLunBaoBeiActivity.this,
			// PhotoActivity.class);
			// intent.putExtra("imgUrls",
			// orderList.getItems().get(parentPostion)
			// .getImgUrls());
			// intent.putExtra("ID", childPosition);
			// startActivityForResult(intent, 101);// (intent);
		}
	}

	private int totalSize;
	int count = 0;
	private int imageLength;
	private boolean isComment;

	public void onBitMap() {
		if (scores.length() <= 0) {
			ByAlert.alert("请输入评分");
			return;
		}
		for (String content : comment) {
			Log.e("comment", content);
			if (TextUtils.isEmpty(content)) {
				isComment = false;
				break;
			} else {
				isComment = true;
			}
		}
		if (isComment == false) {
			ByAlert.alert("请输入评论内容");
			return;
		}
		imageLength = 0;
		for (int i = 0; i < orderList.getItems().size(); i++) {
			if (orderList.getItems().get(i).getImgUrls().size() > 0)
				for (int j = 0; j < orderList.getItems().get(i).getImgUrls()
						.size(); j++) {
					imageLength++;
				}
		}
		buffer = new StringBuffer();

		for (int i = 0; i < orderList.getItems().size(); i++) {
			ids1.add(orderList.getItems().get(i).getPId());

			if (orderList.getItems().get(i).getImgUrls().size() > 0) {
				totalSize = 0;
				while (totalSize < orderList.getItems().get(i).getImgUrls()
						.size()) {
					uploadImage(i, totalSize);
					totalSize++;
				}
			}
		}
	}

	public synchronized void uploadImage(int i, int totalSize) {
		ImageCompressAndUpload.getInstance().execute(
				orderList.getItems().get(i).getImgUrls().get(totalSize),
				new OnUploadlistener() {

					@Override
					public synchronized void OnSuccess(String resultData) {
						count++;
						ids2.add(resultData);
						if (count == imageLength) {
							try {
								for (int j = 0; j < orderList.getItems().size(); j++) {
									// buffer.append(orderList.getItems().get(j)
									// .getPId()
									// + "-");

									for (int k = 0; k < orderList.getItems()
											.get(j).getImgUrls().size(); k++) {
										Log.e("!!!!", ids2.size() + "");
										if (k < orderList.getItems().get(j)
												.getImgUrls().size() - 1)
											buffer.append(ids2.get(zz) + "-");
										else
											buffer.append(ids2.get(zz) + ",");
										zz++;
										System.out.println("内层循环" + buffer);
									}
								}
							} catch (Exception e) {
								// TODO: handle exception
							}
							buffer.deleteCharAt(buffer.length() - 1);
							submitCommnet();
						}
						Log.e("img_id", resultData);
					}

					@Override
					public void OnError(String resultData) {
						ByAlert.alert("发表出错了╰(￣▽￣)╭");
					}
				}, "bbs");
	}

	protected void submitCommnet() {
		// TODO Auto-generated method stub
		String _pid = pid.toString().substring(0, pid.toString().length() - 1);
		String _orderCode = orderCode;
		String _scores = scores.toString().substring(0,
				scores.toString().length() - 1);
		String _buffer = null;
		String _pskuId = null;
		String[] _comment = comment;
		for (int i = 0; i < _comment.length; i++) {
			Log.e("comment", _comment[i]);
		}
		if (pskuId.length() > 0) {
			_pskuId = pskuId.toString().substring(0, pskuId.length() - 1);
		}
		if (buffer.length() > 0)
			_buffer = buffer.toString().substring(0,
					buffer.toString().length() - 1);
		System.out.println("_pid:" + _pid + "_orderCode:" + _orderCode
				+ "_scores:" + _scores + "_comment:" + _comment + "_pskuId:"
				+ _pskuId + "_buffer:" + _buffer);
		orderPresenter.commentOrder(uid, _pid, _orderCode, _pskuId,
				groupId.substring(0, groupId.length() - 1),
				packageId.substring(0, packageId.length() - 1), _scores,
				comment, _buffer, "", "", "");
	}

	// }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, View parent) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					cameraPermission();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					storePermission();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}

	class PhotoSelect implements PhotoSelectListener {

		@Override
		public void onPhotoSelectFinish(List<String> paths) {
			for (String string : paths) {
				// XImageLoader.load("file://" + string,
				// (ImageView) v.findViewById(R.id.img));
				imgUrls.add(string);

			}
			orderList.getItems().get(parentPosition)
					.addImgUrls((ArrayList<String>) paths);
			// adapter=new GridViewAdapter(PingLunBaoBeiActivity.this,imgUrls);
			// aiWuJiaGridView.setAdapter(adapter);
			adapter2.notifyDataSetChanged();
		}

	}

	private static final int TAKE_PICTURE = 0x000000;
	private String path = "";
	public String addr;

	public void photo() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File file = new File(Environment.getExternalStorageDirectory()
				+ "/myimage/", String.valueOf(System.currentTimeMillis())
				+ ".jpg");
		path = file.getPath();
		Uri imageUri = Uri.fromFile(file);
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(openCameraIntent, TAKE_PICTURE);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			if (orderList.getItems().get(parentPosition).getImgUrls().size() < 9
					&& resultCode == -1) {
				imgUrls.add(path);
				orderList.getItems().get(parentPosition).addImgUrls(imgUrls);
				adapter2.notifyDataSetChanged();
			}
		case 101:
			if (orderList.getItems().get(parentPosition).getImgUrls().size() < 9
					&& resultCode == 102) {
				orderList.getItems().get(parentPosition)
						.setImgUrls(data.getStringArrayListExtra("arrayList"));
				adapter2.notifyDataSetChanged();
			}
			break;
		}
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		ByAlert.alert(entity.getData() + "");
		if (entity != null) {
			if (entity.getEventType() == OrderPresenter.CommentOrderSuccess) {
				ByAlert.alert(entity.getData() + "");
				// edtcontext.setText("");
				Intent intent = new Intent(OrderFragment.REFRESH_UI);
				sendBroadcast(intent);
				finish();
				adapter.notifyDataSetChanged();
			} else if (entity.getEventType() == OrderPresenter.CommentOrderFail) {
				ByAlert.alert(entity.getData() + "");
			}
		}
	}

	public void cameraPermission() {
		if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

			// 如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
			if (ActivityCompat.shouldShowRequestPermissionRationale(this,
					Manifest.permission.CAMERA)) {
				Toast.makeText(this, "请去设置给小萌添加个权限，否则打不开相机。",
						Toast.LENGTH_SHORT).show();
			} else {
				// 进行权限请求
				ActivityCompat.requestPermissions(this,
						new String[] { Manifest.permission.CAMERA },
						EXTERNAL_CAMERA_REQ_CODE);
			}
		} else {
			photo();
			popupWindows.dismiss();
		}
	}

	public void storePermission() {
		if (ContextCompat.checkSelfPermission(this,
				Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

			// 如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
			if (ActivityCompat.shouldShowRequestPermissionRationale(this,
					Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
				Toast.makeText(this, "请去设置给小萌添加个权限，否则不能读取相册。",
						Toast.LENGTH_SHORT).show();
			} else {
				// 进行权限请求
				ActivityCompat.requestPermissions(this, new String[] {
						Manifest.permission.WRITE_EXTERNAL_STORAGE,
						Manifest.permission.READ_EXTERNAL_STORAGE },
						EXTERNAL_STORE_REQ_CODE);
			}
		} else {

			new PhotoSelectFragment(new PhotoSelect(), 9).show(
					getSupportFragmentManager(), null);

		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] arg1,
			int[] grantResults) {
		// TODO Auto-generated method stub
		super.onRequestPermissionsResult(requestCode, arg1, grantResults);

		switch (requestCode) {

		case EXTERNAL_CAMERA_REQ_CODE: {
			if (grantResults == null || "".equals(grantResults)) {
				return;
			} else {
				if (grantResults.length > 0
						&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					// 申请成功，进行相应操作
					photo();
					popupWindows.dismiss();
				} else {
					// 申请失败，可以继续向用户解释。

				}
			}
			return;
		}
		case EXTERNAL_STORE_REQ_CODE: {

			if (grantResults.length > 0
					&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
				// 申请成功，进行相应

				PhotoSelectFragment photoSelectFragment = new PhotoSelectFragment(
						new PhotoSelect(), 9);
				photoSelectFragment.show(getSupportFragmentManager(), null);

			} else {
				// 申请失败，可以继续向用户解释。

			}
			return;
		}
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle arg0) {
		// TODO Auto-generated method stub
		// super.onSaveInstanceState(arg0);
	}

}
